import React, { useContext, useReducer } from "react";


export const createReducerContext = (reducer, initialState) => {
  // 在内部定义一个 StoreContext，用于传递 store
  const StoreContext = React.createContext(initialState);

  // Provider
  const ShareStateProvider = (props) => {
    const [store, dispatch] = useReducer(reducer, initialState);
    return (
      <StoreContext.Provider value={{ store, dispatch }}>
        {props.children}
      </StoreContext.Provider>
    );
  };
  
  
  // 用于取数据的自定义 Hook
  const useShareState = partialFn => {
      const { store, dispatch } = useContext(StoreContext);
      return {
          data: partialFn ? partialFn(store) : store,
          dispatch,
        };
    };
    
    return [ShareStateProvider, useShareState];
};
    